import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/exam/dto/assessment_question_details.dart';
import 'package:ichinesereader/exam/widgets/BGDashedRectWidget.dart';
import 'package:ichinesereader/exam/widgets/BGExamImageWidget.dart';
import 'package:ichinesereader/exam/widgets/BGSinglePlayer.dart';
import 'package:ichinesereader/utils/StrUtil.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/buttons/debouncedMaterialButton.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/widgets/tools/pdfviewer.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/widgets/SampleAudioPlayer.dart';
import 'package:ichinesereader/models/assessment/assessmentGradingDto.dart';
import '../../models/assessment/questionRecordSection.dart';
import '../../themes/appTheme.dart';
import '../../widgets/buttons/floatingActionButtonsTeacherSwitchClass.dart';

class EvaluationRecordReviewPage extends StatefulWidget {
  @override
  State<EvaluationRecordReviewPage> createState() =>
      _EvaluationRecordReviewPageState();
}

class _EvaluationRecordReviewPageState
    extends State<EvaluationRecordReviewPage> {
  final AssessmentsController controller = Get.find();

  // 题号公用字体样式
  final TextStyle titleNumStyle = TextStyle(
      fontSize: 17,
      color: (Get.isDarkMode ? Color(0xFF757575) : Colors.black87),
      fontWeight: FontWeight.w600);

  @override
  void dispose() {
    controller.clearAssessmentQuestionRecordInfo();
    controller.allJson.clear();
    controller.writtenJson.clear();
    controller.oralJson.clear();
    BGSinglePlayer().stop();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build teacher evaluation test record review page');

    Map? argument = Get.arguments;
    return Scaffold(
        backgroundColor:
            Get.isDarkMode ? AppTheme.colors.darkTheme2 : Colors.white,
        appBar: CustomAppBar(
            title: (argument == null || argument["title"] == null)
                ? 'Review'.tr
                : argument["title"]),
        floatingActionButton: FloatingActionButtonsTeacherSwitchClass(),
        body: Scrollbar(
            thickness: 10,
            child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                primary: true,
                child: controller.obx(
                  (data) {
                    return Container(
                      padding: const EdgeInsets.all(24),
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: _createMainWidget()),
                    );
                  },
                ))));
  }

  List<Widget> _createMainWidget() {
    List<Widget> options = [];
    Map? argument = Get.arguments;
    final AssessmentsController controller = Get.find();
    if (controller.assessmentQuestionRecordInfo.value.list == null) {
      options.add(Text(''));
    } else {
      bool isHaveNum = false;
      QuestionDetails question = controller.assessmentQuestionRecordInfo.value.list![0].questions![0];
      if (question.question![0].head != null && question.question![0].head!.text != null && question.question![0].head!.text!.startsWith('1')) {
        if (question.question!.length > 1 &&
            question.question![1].head != null &&
            question.question![1].head!.text != null &&
            question.question![1].head!.text!.startsWith('2')) {
          isHaveNum = true;
        }
      }
      for (int i = 0; i < controller.assessmentQuestionRecordInfo.value.list!.length; i++) {
        QuestionRecordSection? section = controller.assessmentQuestionRecordInfo.value.list?[i];
        for (int j = 0; j < section!.questions!.length; j++) {
          QuestionDetails question = section.questions![j];
          for (int k = 0; k < question.question!.length; k++) {
            QuestionItem element = question.question![k];
            String questionTitleNum = '';
            if (controller.assessmentQuestionRecordInfo.value.list!.length == 1) {
              questionTitleNum = (j + 1).toString() + '.';
              if (question.question!.length > 1) questionTitleNum += (k + 1).toString();
            } else {
              if (isHaveNum) {
                if (j == 0 && k == 0) questionTitleNum = 'P' + (i + 1).toString();
              } else {
                questionTitleNum = (i + 1).toString() + '-' + (j + 1).toString() + '.';
                if (question.question!.length > 1) questionTitleNum += (k + 1).toString();
              }
            }
            Widget typeWidget = SizedBox();
            switch (element.type) {
              case QuestionItem.QUESTION_TYPE_SPEECH:
                typeWidget =
                    _buildSpeech(element, question.content, questionTitleNum);
                break;
              case QuestionItem.QUESTION_TYPE_SORT:
                typeWidget =
                    _buildSort(element, question.content, questionTitleNum);
                break;
              case QuestionItem.QUESTION_TYPE_WRITE:
                typeWidget = _buildWrite(element, question.content,
                    question.id ?? '', questionTitleNum);
                break;
              case QuestionItem.QUESTION_TYPE_SPEAK:
                typeWidget = _buildSpeak(element, question.content,
                    question.id ?? '', questionTitleNum);
                break;
              case QuestionItem.QUESTION_TYPE_OPTION:
              case QuestionItem.QUESTION_TYPE_JUDGE:
                typeWidget =
                    _buildOption(element, question.content, questionTitleNum);
                break;
              case QuestionItem.QUESTION_TYPE_MATCH:
              case QuestionItem.QUESTION_TYPE_GROUP:
                typeWidget =
                    _buildMatch(element, question.content, questionTitleNum);
                break;
              case QuestionItem.QUESTION_TYPE_INPUT:
              case QuestionItem.QUESTION_TYPE_FILL:
                typeWidget =
                    _buildInput(element, question.content, questionTitleNum);
                break;
            }
            options.add(typeWidget);
          }
        }
      }

      options.add(Visibility(
          visible: (argument == null || argument["status"] == null)
              ? false
              : argument["status"] == 'SUBMITTED',
          child:
              Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
            MaterialButton(
              color: Color(0xFFD6D6D6),
              child: Text(
                "CANCEL".tr,
                style: TextStyle(
                    fontFamily: 'Noto Sans SC',
                    color: Colors.black54,
                    fontWeight: FontWeight.w600),
              ),
              onPressed: () {
                Get.back();
              },
            ),
            DebouncedMaterialButton(
                debounceTimeMs: 1200,
                color: Color(0xFF2A9744),
                child: Text(
                  "SUBMIT".tr,
                  style: TextStyle(
                      fontFamily: 'Noto Sans SC',
                      color: Colors.white,
                      fontWeight: FontWeight.w600),
                ),
                onPressed: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                  // bool isAllScore = true;
                  // controller.writtenJson.forEach((element) {
                  //   if (int.parse(element['score'].toString()) == 0) {
                  //     isAllScore = false;
                  //   }
                  // });
                  // controller.oralJson.forEach((element) {
                  //   if (int.parse(element['score'].toString()) == 0) {
                  //     isAllScore = false;
                  //   }
                  // });
                  // if (isAllScore) {
                  AssessmentGradingDto dto = AssessmentGradingDto();
                  dto.submit = true;
                  dto.questionRecordId = Get.arguments['recordId'];
                  dto.userName = Get.arguments['userName'];
                  dto.writtenJson = json.encode(controller.writtenJson);
                  if (controller.writtenJson.isEmpty) dto.writtenJson = '';
                  dto.oralJson = json.encode(controller.oralJson);
                  if (controller.oralJson.isEmpty) dto.oralJson = '';
                  controller.submitAssessmentRecordGrading(dto);
                  Future.delayed(const Duration(milliseconds: 1500), () {
                    Get.back(result: {'isRefresh': true});
                  });
                  // } else {
                  //   Get.snackbar('Message'.tr, 'Please complete all scoring.'.tr,
                  //       backgroundColor: Theme.of(context).primaryColor,
                  //       colorText: Theme.of(context).primaryColorLight,
                  //       snackPosition: SnackPosition.BOTTOM);
                  // }
                })
          ])));
    }
    return options;
  }

  Widget _buildSpeech(
      QuestionItem element, QuestionContent? content, String questionTitleNum) {
    List<Widget> options = [];
    Map? argument = Get.arguments;
    bool isUndone = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'UNDONE');
    bool isNew = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'NEW');
    options.add(_buildSkillInfoWidget(element, false));
    if(element.number == 1) options.add(_buildContentInfoWidget(content, questionTitleNum));
    options.add(_buildReferenceWidget(element.reference));
    options.add(Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildHeadInfoWidget(element, questionTitleNum, 'Speech'),
        //AI口语测试题示意图标
        SizedBox(
            width: 45,
            height: 45,
            child: Image.asset("assets/images/evaluation/ai_speaking.png")),
      ],
    ));
    if (element.answer == null || element.answer!.isEmpty) {
      if (!isUndone && !isNew) {
        options.add(SizedBox(height: 15));
        options.add(Text('No Recording Submitted.'.tr,
            style: TextStyle(
                fontFamily: 'Noto Sans SC',
                fontSize: 21,
                fontWeight: FontWeight.w700)));
        options.add(SizedBox(height: 15));
      }
    } else {
      options.add(Row(
        children: [
          Text('AI Score: '.tr,
              style: TextStyle(
                  fontFamily: 'Noto Sans SC',
                  fontSize: 22,
                  fontWeight: FontWeight.w700)),
          Text(element.intelligenceScore.toString(),
              style: TextStyle(
                  fontFamily: 'Noto Sans SC',
                  fontSize: 22,
                  fontWeight: FontWeight.w700,
                  color: Colors.red))
        ],
      ));
      options.add(SizedBox(height: 10));
      options.add(
        Text('Student Recording: '.tr,
            style: TextStyle(
              fontFamily: 'Noto Sans SC',
              fontSize: 21,
            )),
      );
      options.add(SizedBox(height: 10));
      options.add(SampleAudioPlayer(
          name: 'audioPlayerEvaluation',
          audioUrl: '',
          audioId: element.answer![0]));
      options.add(SizedBox(height: 15));
    }
//AI 跟读测试题框
    return CardWidget(
        child: Container(
      color: Colors.transparent,
      margin: EdgeInsets.only(left: 20),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start, children: options),
    ));
  }

  Widget _buildOption(
      QuestionItem element, QuestionContent? content, String questionTitleNum) {
    List<Widget> options = [];
    bool isAllRight = true;
    List selectOptions = [];
    List solutionList = [];
    List answerList = [];

    Map? argument = Get.arguments;
    bool isUndone = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'UNDONE');
    bool isNew = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'NEW');
    if (isUndone && (element.solution == null || element.solution!.isEmpty)) {
      element.solution = element.answer;
    }
    if (isNew && (element.answer == null || element.answer!.isEmpty)) {
      element.answer = element.solution;
    }

    if (element.solution != null && element.solution!.isNotEmpty) {
      solutionList = element.solution!;
    }
    if (element.answer != null && element.answer!.isNotEmpty) {
      answerList = element.answer!;
    }

    if (element.body != null &&
        element.body!.isNotEmpty &&
        element.body?.first != null) {
      selectOptions = element.body!.first;
      selectOptions.sort((a, b) => a.baseValue.compareTo(b.baseValue));
    }
    if (solutionList.isNotEmpty && solutionList.length == answerList.length) {
      for (int i = 0; i < solutionList.length; i++) {
        String tempStr = solutionList[i];
        if (!answerList.contains(tempStr)) {
          isAllRight = false;
        }
      }
    } else {
      isAllRight = false;
    }
    options.add(_buildSkillInfoWidget(element, true));
    if(element.number == 1) options.add(_buildContentInfoWidget(content, questionTitleNum));
    options.add(_buildReferenceWidget(element.reference));
    options.add(Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        //初级听力测试测验题左上角的LIST的图标
        Text('  ' + questionTitleNum, style: titleNumStyle),
        Container(
          padding: EdgeInsets.all(6.0),
          margin: EdgeInsets.only(left: 12.0),
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Get.isDarkMode
                ? Get.theme.primaryColorDark
                : Get.theme.primaryColor,
          ),
          child: SvgPicture.asset(
            'assets/images/evaluation/type_option.svg',
            width: 18.0,
            height: 18.0,
            colorFilter: ColorFilter.mode(
                Get.isDarkMode ? Colors.black : Get.theme.primaryColorLight,
                BlendMode.srcIn),
            //color: Get.isDarkMode ? Colors.black : Get.theme.primaryColorLight,
          ),
        ),
        // SizedBox(width: 5),
        _buildHeadCheckIconWidget(isAllRight),
        // SizedBox(width: 10),
        _buildHeadInfoWidget(element, '', 'Option'),
        //Expanded(child: SizedBox()),
      ],
    ));

    options.add(SizedBox(height: 10));
    options.add(Padding(
        padding: EdgeInsets.only(left: 20, right: 20),
        child: ListView.builder(
            itemCount: selectOptions.length,
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemBuilder: (context, index) {
              QuestionContent item = selectOptions[index];
                    return _buildOptionItem(
                        item,
                        solutionList.contains(item.baseValue),
                        answerList.contains(item.baseValue));
            })));

    return CardWidget(
        child: Container(
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start, children: options),
    ));
  }

  Widget _buildOptionItem(
      QuestionContent body, bool isSolution, bool isAnswer) {
    List<Widget> options = [];
    String? show = body.show;
    if (show != null) {
      if (isAnswer) {
        //初级听力测验题左侧绿色的勾选正确图示
        options.add(SizedBox(
          width: 60,
          child: Icon(isSolution ? Icons.check : Icons.close,
              color: isSolution ? Colors.green : Colors.red, size: 60),
        ));
        // SizedBox(
        // width: 60,
        // height: 40,
        // child: Column(
        //   children: [
        //     Icon(isSolution ? Icons.check : Icons.close,
        //         color: isSolution ? Colors.greenAccent : Colors.red, size: 45)
        //   ],
        // )));
      } else {
        options.add(SizedBox(
          width: 60,
        ));
      }

      if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_TEXT)) {
        options.add(Expanded(
            child: Text(body.text ?? '',
                style: TextStyle(
                    fontFamily: 'Noto Sans SC',
                    fontSize: 18,
                    height: 1.8,
                    color: isSolution
                        ? Color(0xFF409DAB)
                        : (Get.isDarkMode ? Color(0xFF757575) : Colors.black87),
                    fontWeight: FontWeight.w500))));
      }
      if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_IMAGE)) {
        options
            .add(BGExamImageWidget(imgUrl: body.image, source: 'OptionItem'));
      }
    }
    return Row(children: options);
  }

  Widget _buildMatch(
      QuestionItem element, QuestionContent? content, String questionTitleNum) {
    List<Widget> options = [];
    List<bool> judge = [];
    List leftList = [];
    List showRightList = [];
    List rightList = [];
    bool isAllRight = true;
    Map? argument = Get.arguments;
    bool isUndone = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'UNDONE');
    bool isNew = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'NEW');
    if (element.body != null &&
        element.body?.first != null &&
        element.body?[1] != null) {
      List solutionList = [];
      leftList = element.body?.first ?? [];
      List tempRList = element.body?[1] ?? [];
      for (int i = 0; i < tempRList.length; i++) {
        QuestionContent body1 = tempRList[i];
        rightList.add(body1);
      }
      if (isNew && (element.answer == null || element.answer!.isEmpty)) {
        element.answer = element.solution;
      }
      if (element.answer != null && element.answer!.isNotEmpty) {
        for (int i = 0; i < leftList.length; i++) {
          QuestionContent leftItem = leftList[i];
          bool isHave = false;
          for (int j = 0; j < element.answer!.length; j++) {
            String answerStr = element.answer![j];
            List tempList = answerStr.split('|');
            if (leftItem.baseValue != null &&
                (tempList.first == leftItem.baseValue! ||
                    tempList.last == leftItem.baseValue!)) {
              for (int k = 0; k < rightList.length; k++) {
                QuestionContent rightItem = rightList[k];
                if (rightItem.baseValue != null &&
                    (tempList.last == rightItem.baseValue! ||
                        tempList.first == rightItem.baseValue!)) {
                  isHave = true;
                  showRightList.add(rightItem);
                }
              }
            }
          }
          if (!isHave) {
            showRightList.add(QuestionContent());
          }
        }
      }
      for (int i = 0; i < showRightList.length; i++) {
        if (rightList.contains(showRightList[i])) {
          rightList.remove(showRightList[i]);
        }
      }
      if (element.solution != null && element.solution!.isNotEmpty) {
        for (int i = 0; i < leftList.length; i++) {
          QuestionContent leftItem = leftList[i];
          for (int j = 0; j < element.solution!.length; j++) {
            String answerStr = element.solution![j];
            List tempList = answerStr.split('|');
            if (leftItem.baseValue != null &&
                (tempList.first == leftItem.baseValue! ||
                    tempList.last == leftItem.baseValue!)) {
              for (int k = 0; k < showRightList.length; k++) {
                QuestionContent rightItem = showRightList[k];
                if (rightItem.baseValue != null &&
                    (tempList.last == rightItem.baseValue! ||
                        tempList.first == rightItem.baseValue!)) {
                  solutionList.add(rightItem);
                }
              }
              for (int k = 0; k < rightList.length; k++) {
                QuestionContent rightItem = rightList[k];
                if (rightItem.baseValue != null &&
                    (tempList.last == rightItem.baseValue! ||
                        tempList.first == rightItem.baseValue!)) {
                  solutionList.add(rightItem);
                }
              }
            }
          }
        }
      }

      if (solutionList.isNotEmpty &&
          showRightList.isNotEmpty &&
          solutionList.length == showRightList.length) {
        for (int i = 0; i < element.solution!.length; i++) {
          if (showRightList[i].baseValue != null &&
              solutionList[i].baseValue != null &&
              solutionList[i].baseValue == showRightList[i].baseValue) {
            judge.add(true);
          } else {
            judge.add(false);
            isAllRight = false;
          }
        }
      } else {
        isAllRight = false;
      }
    }
    options.add(_buildSkillInfoWidget(element, true));
    if(element.number == 1) options.add(_buildContentInfoWidget(content, questionTitleNum));
    options.add(_buildReferenceWidget(element.reference));
    options.add(Row(children: [
      Text('  ' + questionTitleNum, style: titleNumStyle),
      Expanded(
          child: Container(
        margin: EdgeInsets.symmetric(horizontal: 9.0),
        padding: EdgeInsets.symmetric(vertical: 6.0),
        decoration: BoxDecoration(
            color: Get.isDarkMode
                ? AppTheme.colors.darkTheme2
                : Colors.black.withOpacity(0.1)),
        child: Row(
          children: [
            //阅读测验连连看左上角的图标区
            Container(
              padding: EdgeInsets.all(6.0),
              margin: EdgeInsets.only(left: 12.0),
              decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Get.isDarkMode
                      ? Get.theme.primaryColorDark
                      : Get.theme.primaryColor),
              child: SvgPicture.asset(
                'assets/images/evaluation/type_match.svg',
                width: 12,
                height: 12,
                colorFilter: ColorFilter.mode(
                    Get.isDarkMode ? Colors.black : Get.theme.primaryColorLight,
                    BlendMode.srcIn),
                //color: Get.isDarkMode ? Colors.black : Get.theme.primaryColorLight,
              ),
            ),
            _buildHeadCheckIconWidget(isAllRight),
            //上方提示文字
            _buildHeadInfoWidget(element, '', 'Match'),
          ],
        ),
      ))
    ]));
    options.add(SizedBox(height: 10));
    options.add(Container(
        padding: EdgeInsets.only(left: 20, right: 20),
        child: Row(children: [
          SizedBox(
              width: 30,
              child: Visibility(
                  visible: !(isUndone || isNew),
                  child: ListView.builder(
                      itemCount: leftList.length,
                      physics: NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemBuilder: (context, index) {
                        return Container(
                            height: 100,
                            child: Icon(
                                (judge.length > index ? judge[index] : false)
                                    ? Icons.check
                                    : Icons.close,
                                color: (judge.length > index
                                        ? judge[index]
                                        : false)
                                    ? Color(0xFF409DAB)
                                    : Colors.red,
                                size: 26));
                      }))),
          SizedBox(width: 15),
          SizedBox(
              width: 190,
              child: ListView.builder(
                  itemCount: leftList.length,
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemBuilder: (context, index) {
                    return _buildMatchList(leftList[index], true);
                  })),
          SizedBox(width: 30),
          SizedBox(
              width: 100,
              child: ListView.builder(
                  itemCount: showRightList.length,
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemBuilder: (context, index) {
                    return _buildMatchList(showRightList[index], false);
                  })),
          Visibility(
            visible: rightList.isNotEmpty,
            child: Container(
                width: 100,
                padding: EdgeInsets.only(left: 20),
                child: ListView.builder(
                    itemCount: rightList.length,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      return _buildMatchList(rightList[index], false);
                    })),
          )
        ])));
    return CardWidget(
        child: Container(
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start, children: options),
    ));
  }

  Widget _buildMatchList(QuestionContent body, bool isLeft) {
    Widget options = SizedBox(width: 100, height: 100);
    String? show = body.show;
    if (show != null) {
      if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_TEXT)) {
        options = Container(
            height: 100,
            width: isLeft ? 190 : 100,
            alignment: Alignment.center,
            child: Text(body.text ?? '',
                style: TextStyle(fontFamily: 'Noto Sans SC', fontSize: 14)));
      }
      if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_AUDIO)) {
        options = SizedBox(
            height: 100,
            child: IconButton(
              iconSize: 44,
              icon: const Icon(
                Icons.play_circle,
                color: Colors.blue,
              ),
              onPressed: () {
                if (StrUtil.hasValue(body.audio)) {
                  BGSinglePlayer().play(body.audio);
                }
              },
            ));
      }
      if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_IMAGE)) {
        options = BGExamImageWidget(imgUrl: body.image, source: 'MatchList');
      }
    }
    return Padding(padding: EdgeInsets.only(bottom: 5), child: options);
  }

  Widget _buildSort(
      QuestionItem element, QuestionContent? content, String questionTitleNum) {
    List<Widget> options = [];
    bool isAllRight = true;
    List originalList = element.body!.first;
    List answerList = [];
    List solutionList = [];
    Map? argument = Get.arguments;
    bool isNew = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'NEW');
    if (isNew && (element.answer == null || element.answer!.isEmpty)) {
      element.answer = element.solution;
    }
    if (element.solution != null && element.solution!.isNotEmpty) {
      solutionList = element.solution!.first.split('|');
    }
    if (element.answer!.isNotEmpty && solutionList.isNotEmpty) {
      answerList = element.answer!.first.split('|');
      for (int i = 0; i < answerList.length; i++) {
        if (i < solutionList.length && answerList[i] != solutionList[i]) {
          isAllRight = false;
        }
      }
    } else {
      isAllRight = false;
    }
    options.add(_buildSkillInfoWidget(element, false));
    if(element.number == 1) options.add(_buildContentInfoWidget(content, questionTitleNum));
    options.add(_buildReferenceWidget(element.reference));
    options.add(Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('  ' + questionTitleNum + ' ', style: titleNumStyle),
        SvgPicture.asset(
          'assets/images/evaluation/type_sort.svg',
          width: 40,
          height: 40,
        ),
        //SizedBox(width: 5),
        _buildHeadCheckIconWidget(isAllRight),
        //SizedBox(width: 10),
        _buildHeadInfoWidget(element, '', 'Sort'),
        //Expanded(child: SizedBox()),
      ],
    ));
    options.add(SizedBox(height: 10));
    options.add(Container(
      height: 30,
      alignment: Alignment.center,
      padding: EdgeInsets.only(left: 10),
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: originalList.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return Padding(
                padding: EdgeInsets.only(left: 5, right: 5),
                child: Text(originalList[index].text ?? '',
                    style:
                        TextStyle(fontFamily: 'Noto Sans SC', fontSize: 15)));
          }),
    ));

    options.add(Container(
      alignment: Alignment.center,
      height: 30,
      child: Icon(
        Icons.keyboard_arrow_down,
        color: Colors.black,
      ),
    ));

    options.add(Container(
      height: 50,
      alignment: Alignment.center,
      padding: EdgeInsets.only(left: 10),
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: solutionList.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return _buildSortItem(
                answerList.length > index ? answerList[index] : '',
                solutionList[index]);
          }),
    ));

    return CardWidget(
        child: Container(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: options)));
  }

  Widget _buildSortItem(String answerStr, String solutionStr) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Padding(
            padding: EdgeInsets.only(left: 5, right: 5),
            child: Text(answerStr,
                style: TextStyle(fontFamily: 'Noto Sans SC', fontSize: 15))),
        Icon((answerStr == solutionStr) ? Icons.check : Icons.close,
            color: (answerStr == solutionStr) ? Color(0xFF409DAB) : Colors.red,
            size: 26)
      ],
    );
  }

  Widget _buildInput(
      QuestionItem element, QuestionContent? content, String questionTitleNum) {
    List<Widget> options = [];
    List<String> blankList = [];
    bool isAllRight = true;
    String textStr = element.head?.text ?? '';
    List inputList = textStr.split('_____');
    if (inputList.length == 1) {
      inputList = textStr.split(RegExp(r'<u>\[[\d+]\]</u>'));
    }
    List answerList = [];
    List solutionList = [];
    List judgeList = [];
    Map? argument = Get.arguments;
    bool isNew = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'NEW');
    if (isNew && (element.answer == null || element.answer!.isEmpty)) {
      element.answer = element.solution;
    }
    if (element.solution != null && element.solution!.isNotEmpty) {
      solutionList = element.solution!;
    }
    if (element.answer!.isNotEmpty &&
        solutionList.isNotEmpty &&
        inputList.length > 0) {
      if (element.answer![0].startsWith('[1]')) {
        answerList = element.answer!;
      } else {
        for (int i = 0; i < element.answer!.length; i++) {
          String indexStr = '[${i + 1}]';
          answerList.add(indexStr + element.answer![i]);
        }
      }

      for (int i = 1; i < inputList.length; i++) {
        String indexStr = '[$i]';
        for (int j = 0; j < answerList.length; j++) {
          String noBlankStr =
              answerList[j].replaceAll(RegExp(r'\s+\b|\b\s'), '');
          if (noBlankStr.contains(indexStr)) {
            indexStr = '[-1]';
            bool isHave = false;
            solutionList.forEach((element) {
              if (noBlankStr == element.replaceAll(RegExp(r'\s+\b|\b\s'), '')) {
                isHave = true;
                judgeList.add(true);
                return;
              }
            });
            if (!isHave) {
              isAllRight = false;
              judgeList.add(false);
            }
          }
        }
      }
    } else {
      isAllRight = false;
      if (element.answer != null && element.answer!.isNotEmpty) {
        if (element.answer![0].startsWith('[1]')) {
          answerList = element.answer!;
        } else {
          for (int i = 0; i < element.answer!.length; i++) {
            String indexStr = '[${i + 1}]';
            answerList.add(indexStr + element.answer![i]);
          }
        }
      } else {
        for (int i = 1; i < inputList.length; i++) {
          answerList.add('[$i]');
        }
      }
    }
    String _textHtmlWidget(String text) {
      return text.replaceAll('\n', '<br/>');
    }

    String _textAnswerWidget(String text, int i) {
      if (judgeList.length == answerList.length &&
          i < inputList.length - 1 &&
          !judgeList[i]) {
        return '<u style="color: #FF0000;">&emsp;$text&emsp;&times;&emsp;</u>';
      }
      return '<u style="color: #4F955B;">&emsp;$text&emsp;&radic;&emsp;</u>';
    }

    for (int i = 0; i < inputList.length; i++) {
      blankList.add(_textHtmlWidget(inputList[i]));
      String indexStr = '[${i + 1}]';
      for (var element in answerList) {
        if (element.toString().startsWith(indexStr)) {
          String noBlankStr = element.replaceAll(RegExp(r'\s+\b|\b\s'), '');
          blankList.add(_textAnswerWidget(
              noBlankStr.replaceRange(0, indexStr.length, ''), i));
          break;
        }
      }
    }
    String addStr = '';
    blankList.forEach((element) {
      addStr += element;
    });
    options.add(_buildSkillInfoWidget(element, true));
    if(element.number == 1) options.add(_buildContentInfoWidget(content, questionTitleNum));
    options.add(_buildReferenceWidget(element.reference));
    options.add(SizedBox(height: 10));
    options.add(Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
      //SizedBox(width: 5),
      Text('  ' + questionTitleNum, style: titleNumStyle),
      _buildHeadCheckIconWidget(isAllRight),
      //SizedBox(width: 10),
      Expanded(child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          HtmlWidget(addStr,
              textStyle: TextStyle(
                  fontFamily: 'Noto Sans SC',
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                      color:
                          (Get.isDarkMode ? Color(0xFF757575) : Colors.black87),
                  height: 1.8,
                  wordSpacing: 1.5)),
          Visibility(
              visible: element.head!.audio != null,
              child: IconButton(
                tooltip: element.reference?.text,
                iconSize: 40,
                icon: Icon(
                  Icons.volume_up,
                  color: (element.reference != null &&
                          element.reference!.text != null &&
                          element.reference!.text!.isNotEmpty)
                      ? Colors.deepOrange
                      : Colors.orange,
                ),
                onPressed: () {
                  BGSinglePlayer().play(element.head!.audio);
                },
              )),
          BGExamImageWidget(imgUrl: element.head!.image, source: 'HeadInput')
        ],
      )),
      SizedBox(
          width: 40,
          height: 40,
          child: Image.asset("assets/images/evaluation/writing.png")),
    ]));
    return CardWidget(
        child: Container(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: options)));
  }

  Widget _buildSpeak(QuestionItem element, QuestionContent? content,
      String questionId, String questionTitleNum) {
    List<Widget> options = [];
    Map? argument = Get.arguments;
    bool isUndone = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'UNDONE');
    bool isNew = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'NEW');
    options.add(_buildSkillInfoWidget(element, false));
    if(element.number == 1) options.add(_buildContentInfoWidget(content, questionTitleNum));
    options.add(_buildReferenceWidget(element.reference));
    options.add(SizedBox(height: 10));
    options.add(Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        _buildHeadInfoWidget(element, questionTitleNum, 'Speak'),
        SizedBox(
            width: 40,
            height: 40,
            child: Image.asset("assets/images/evaluation/speaking.png")),
      ],
    ));
    if (element.answer == null || element.answer!.isEmpty) {
      if (!isUndone && !isNew) {

 		options.add(SizedBox(height: 15));        options.add(Text('No Recording Submitted.'.tr,
            style: TextStyle(
                fontFamily: 'Noto Sans SC',
                fontSize: 22,
                fontWeight: FontWeight.w700)));
        options.add(SizedBox(height: 15));
      }
    } else {
      options.add(SizedBox(height: 10));
      options.add(SampleAudioPlayer(
          name: 'audioPlayerEvaluation',
          audioUrl: '',
          audioId: element.answer![0]));
      options.add(SizedBox(height: 15));
    }

    options.add(SizedBox(height: 10));
    options.add(Visibility(
        visible: (argument == null || argument["status"] == null)
            ? false
            : (argument["status"] == 'SUBMITTED' ||
                argument["status"] == 'COMPLETED'),
        child: buildScoreWidget(questionId, element.number, 'speak')));

    return CardWidget(
        child: Container(
      margin: EdgeInsets.only(left: 20),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start, children: options),
    ));
  }

  Widget _buildWrite(QuestionItem element, QuestionContent? content,
      String questionId, String questionTitleNum) {
    List<Widget> options = [];
    Map? argument = Get.arguments;
    options.add(_buildSkillInfoWidget(element, false));
    if(element.number == 1) options.add(_buildContentInfoWidget(content, questionTitleNum));
    options.add(_buildReferenceWidget(element.reference));
    options.add(SizedBox(height: 10));
    options.add(Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        //写作题图标
        Text(questionTitleNum + ' ', style: titleNumStyle),
        SizedBox(
            width: 42,
            height: 42,
            child: Image.asset("assets/images/evaluation/writing.png")),
        _buildHeadInfoWidget(element, '', 'Write'),
        //Expanded(child: SizedBox()),
      ],
    ));
    options.add(SizedBox(height: 10));
    options.add(SizedBox(
        height: 200,
        child: TextField(
          readOnly: true,
          maxLines: 100,
          minLines: 15,
          controller: TextEditingController(
              text: (element.answer == null || element.answer!.isEmpty)
                  ? 'No content'
                  : element.answer!.first),
          decoration: InputDecoration(
            border: OutlineInputBorder(borderRadius: BorderRadius.circular(5)),
          ),
        )));
    options.add(SizedBox(height: 10));
    options.add(Visibility(
        visible: (argument == null || argument["status"] == null)
            ? false
            : (argument["status"] == 'SUBMITTED' ||
                argument["status"] == 'COMPLETED'),
        child: buildScoreWidget(questionId, element.number, 'write')));

    return CardWidget(
        child: Container(
      margin: EdgeInsets.only(left: 21),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start, children: options),
    ));
  }

  Widget _buildHeadCheckIconWidget(bool isAllRight) {
    Map? argument = Get.arguments;
    bool isUndone = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'UNDONE');
    bool isNew = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'NEW');
    return (isUndone || isNew)
        ? SizedBox(width: 15)
        : Icon(isAllRight ? Icons.check : Icons.close,
            color: isAllRight ? AppTheme.colors.addBtn : Colors.red, size: 24);
  }

  Widget _buildSkillInfoWidget(QuestionItem element, bool isMarginLeft) {
    if (element.skill != null && element.skill!.isNotEmpty) {
      Map firstMap = element.skill!.values.first;
      String firstName = firstMap['name'];
      Map secondMap = firstMap['next'];
      if (secondMap.isNotEmpty) {
        for (int i = 0; i < secondMap.values.length; i++) {
          firstName = firstName +
              ' | ' +
              secondMap.values.toList()[i]['name'].toString();
        }
      }
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: 5),
          Row(
            children: [
              isMarginLeft ? SizedBox(width: 40) : SizedBox(),
              Expanded(child: Text(firstName,
                  style: TextStyle(
                        fontFamily: 'Noto Sans SC',
                        fontSize: 16,
                        height: 1.8,
                        color: (Get.isDarkMode
                            ? Color(0xFF757575)
                            : Colors.black87))),
              )
            ],
          )
        ],
      );
    } else {
      return SizedBox();
    }
  }

  Widget _buildContentInfoWidget(
      QuestionContent? content, String questionTitleNum) {
    List tempList = questionTitleNum.split('.');
    if (tempList.length == 2 &&
        tempList[1] != '' &&
        int.parse(tempList[1]) > 1) {
      return SizedBox();
    }
    bool isBlank = content != null &&
        content.text != null &&
        content.text!.isNotEmpty &&
        content.text! != '<p></p>';
    String? replaceStr = content?.text;
    if (content != null && content.text != null) {
      replaceStr = content.text!.replaceAll('\n', '<br/>');
    }
    return Visibility(
        visible: content?.show != null,
        child: Padding(
            padding: EdgeInsets.fromLTRB(30, 20, 20, 20),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
              Visibility(
                  visible: isBlank,
                  child: Padding(
                      padding: EdgeInsets.only(bottom: 20),
                      child: BGDashedRectWidget(
                          child: Container(
                              width: double.infinity,
                              margin: EdgeInsets.all(20),
                              child: HtmlWidget(replaceStr ?? '',
                                  textStyle: TextStyle(
                                      fontFamily: 'Noto Sans SC',
                                      fontSize: 18,
                                      fontWeight: FontWeight.w600,
                                          color: (Get.isDarkMode
                                              ? Color(0xFF757575)
                                              : Colors.black87),
                                      height: 1.8,
                                      wordSpacing: 1.5)))))),
              Visibility(
                  visible: content?.audio != null,
                  child: Padding(
                      padding: EdgeInsets.only(top: 20, bottom: 10),
                          child: SampleAudioPlayer(
                              name: 'audioPlayerEvaluation',
                              audioUrl: content?.audio ?? ''))),
                  Visibility(
                      visible: content?.image != null,
                      child: BGExamImageWidget(imgUrl: content?.image, source: 'Content'))
            ])));
  }

  Widget _buildHeadInfoWidget(
      QuestionItem element, String questionTitleNum, String source) {
    String? replaceStr = element.head?.text;
    if (element.head != null && element.head!.text != null) {
      replaceStr = element.head!.text!.replaceAll('\n', '<br/>');
    }
    if (questionTitleNum != '') questionTitleNum += ' ';
    return Expanded(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Visibility(
            visible: element.head?.image != null,
            child: BGExamImageWidget(imgUrl: element.head?.image, source: 'Head' + source)),
        RichText(
            text: TextSpan(children: [
          (element.head != null &&
                  element.head!.text != null &&
                  (element.head!.text!.contains('</')))
              ? WidgetSpan(
                  child: HtmlWidget(replaceStr ?? '',
                      textStyle: TextStyle(
                          fontFamily: 'Noto Sans SC',
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: (Get.isDarkMode
                              ? Color(0xFF757575)
                              : Colors.black87),
                          height: 1.8,
                          wordSpacing: 1.5)))
              : TextSpan(
                  text: questionTitleNum + (element.head!.text ?? ''),
                  style: TextStyle(
                      fontFamily: 'Noto Sans SC',
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                      color:
                          (Get.isDarkMode ? Color(0xFF757575) : Colors.black87),
                      height: 1.8,
                      wordSpacing: 1.5)),
          WidgetSpan(
              child: Visibility(
                  visible: element.head!.audio != null,
                  child: Container(
                      padding: EdgeInsets.fromLTRB(6, 4, 6, 0),
                      height: 40,
                      width: 52,
                      child: IconButton(
                        tooltip: element.reference?.text,
                        iconSize: 40,
                        padding: EdgeInsets.zero,
                        icon: Icon(
                          Icons.volume_up,
                          color: (element.reference != null &&
                                  element.reference!.text != null &&
                                  element.reference!.text!.isNotEmpty)
                              ? Colors.deepOrange
                              : Colors.orange,
                        ),
                        onPressed: () {
                          BGSinglePlayer().play(element.head!.audio);
                        },
                      ))))
        ])),
      ],
    ));
  }

  Widget buildScoreWidget(
      String questionId, int? questionNum, String questionType) {
    List<Widget> optionsList = [];
    final AssessmentsController controller = Get.find();
    final box = Hive.box('appconfig');

    RxInt radioGroupValue = 0.obs;
    String writeText = '';
    if (questionNum == null) questionNum = 1;
    Map? argument = Get.arguments;
    bool isCompleted = (argument != null &&
        argument["status"] != null &&
        argument["status"] == 'COMPLETED');
    bool isAP = (argument != null &&
        argument["assessmentType"] != null &&
        argument["assessmentType"] == Constants.AssessmentType_AP);
    if (isCompleted) {
      String write = '';
      String oral = '';

      if (argument["assessmentType"] != null &&
          argument["assessmentType"] == Constants.AssessmentType_EVALUATION &&
          controller.assessmentRecordsGrades.value.examEvalRecord != null) {
        write = controller
                .assessmentRecordsGrades.value.examEvalRecord!.writtenJson ??
            '';
        oral =
            controller.assessmentRecordsGrades.value.examEvalRecord!.oralJson ??
                '';
      }

      if (argument["assessmentType"] != null &&
          argument["assessmentType"] == Constants.AssessmentType_AP &&
          controller.assessmentRecordsGrades.value.examApRecord != null) {
        write = controller
                .assessmentRecordsGrades.value.examApRecord!.writtenJson ??
            '';
        oral =
            controller.assessmentRecordsGrades.value.examApRecord!.oralJson ??
                '';
      }

      if (argument["assessmentType"] != null &&
          argument["assessmentType"] ==
              Constants.AssessmentType_BENCHMARK_TEST &&
          controller.assessmentRecordsGrades.value.examBmRecord != null) {
        write = controller
                .assessmentRecordsGrades.value.examBmRecord!.writtenJson ??
            '';
        oral =
            controller.assessmentRecordsGrades.value.examBmRecord!.oralJson ??
                '';
      }

      if (argument["assessmentType"] != null &&
          argument["assessmentType"] ==
              Constants.AssessmentType_SOCIAL_STUDIES &&
          controller.assessmentRecordsGrades.value.examSsRecord != null) {
        write = controller
                .assessmentRecordsGrades.value.examSsRecord!.writtenJson ??
            '';
        oral =
            controller.assessmentRecordsGrades.value.examSsRecord!.oralJson ??
                '';
      }

      if (write.isNotEmpty) {
        controller.writtenJson =
            json.decode(write).cast<Map<dynamic, dynamic>>();
      }
      if (oral.isNotEmpty) {
        controller.oralJson = json.decode(oral).cast<Map<dynamic, dynamic>>();
      }
      controller.allJson.addAll(controller.writtenJson);
      controller.allJson.addAll(controller.oralJson);
      controller.allJson.forEach((element) {
        if (element['questionId'] == questionId &&
            element['number'] == questionNum) {
          writeText = element['comment'];
          radioGroupValue.value = int.parse(element['score'].toString());
        }
      });
    } else {
      bool isAdd = true;
      controller.allJson.forEach((element) {
        if (element['questionId'] == questionId &&
            element['number'] == questionNum) {
          isAdd = false;
          writeText = element['comment'];
          radioGroupValue.value = int.parse(element['score'].toString());
        }
      });
      if (isAdd) {
        Map singleMap = {
          'questionId': questionId,
          'number': questionNum,
          'comment': '',
          'score': radioGroupValue.value
        };
        if (questionType == 'write') {
          controller.writtenJson.add(singleMap);
        } else if (questionType == 'speak') {
          controller.oralJson.add(singleMap);
        }
        controller.allJson.add(singleMap);
      }
    }
    int num = 11;
    if (isAP) {
      num = 7;
    }
    for (int i = 1; i < num; i++) {
      optionsList.add(SizedBox(
          width: 70,
          child: Obx(() => Row(
                children: [
                  Radio<int>(
                    value: i,
                    activeColor: Colors.blue,
                    groupValue: radioGroupValue.value,
                    onChanged: (value) {
                      if (!isCompleted) {
                        radioGroupValue.value = i;
                        controller.allJson.forEach((element) {
                          if (element['questionId'] == questionId &&
                              element['number'] == questionNum) {
                            element['score'] = i;
                          }
                        });
                      }
                    },
                  ),
                  Text(i.toString(),
                      style: TextStyle(
                          fontFamily: 'Noto Sans SC',
                          fontSize: 18,
                          height: 1.8,
                          color: i == radioGroupValue.value
                              ? Colors.blue
                              : (Get.isDarkMode
                                  ? Color(0xFF757575)
                                  : Colors.black87),
                          fontWeight: FontWeight.w500)),
                ],
              ))));
    }

    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      SizedBox(height: 15),
      IconButton(
          onPressed: () async {
            int ql = box.get('evaluationRecordLevel') ?? 1;
            String pdfaddress = 'assets/docs/wL1-L8.pdf';
            if (questionType == 'write') {
              if (ql > 8) pdfaddress = 'assets/docs/wL9-L17.pdf';
              Get.to(() => PDFViewer(pdfaddress: pdfaddress));
            }
            if (questionType == 'speak') {
              pdfaddress = 'assets/docs/sL1-L8.pdf';
              if (ql > 8) pdfaddress = 'assets/docs/sL9-L17.pdf';
              Get.to(() => PDFViewer(pdfaddress: pdfaddress));
            }
            // showGeneralDialog(
            //     context: Get.context!,
            //     transitionDuration: const Duration(milliseconds: 400),
            //     pageBuilder: (bc, ania, anis) {
            //       return proficiencyGuidelinesPage(questionType);
            //     });
          },
          icon: Icon(Icons.info)),
      SizedBox(height: 15),
      Wrap(spacing: 20, children: optionsList),
      SizedBox(height: 15),
      Container(
          alignment: Alignment.centerLeft,
          child: Text('Comment',
              style: TextStyle(
                  fontFamily: 'Noto Sans SC',
                  fontSize: 18,
                  height: 1.8,
                  color: (Get.isDarkMode ? Color(0xFF757575) : Colors.black87),
                  fontWeight: FontWeight.w600))),
      SizedBox(height: 5),
      SizedBox(
          height: 200,
          child: TextField(
              controller: TextEditingController(
                  text: isCompleted
                      ? (writeText.isEmpty ? 'No comment' : writeText)
                      : writeText),
              readOnly: isCompleted,
              maxLines: 100,
              minLines: 15,
              onChanged: (text) {
                controller.allJson.forEach((element) {
                  if (element['questionId'] == questionId &&
                      element['number'] == questionNum) {
                    element['comment'] = text;
                  }
                });
              },
              decoration: InputDecoration(
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5)),
                  hintText: isCompleted ? '' : 'Writing your Comment')))
    ]);
  }

  Widget _buildReferenceWidget(QuestionContent? reference) {
    String show = '';
    if (reference != null && reference.show != null && reference.show != '') {
      show = reference.show!;
    } else {
      return SizedBox();
    }
    List<Widget> options = [];
    if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_AUDIO)) {
      options.add(SampleAudioPlayer(
        name: 'audioPlayerExam',
        audioUrl: reference.audio ?? '',
      ));
      options.add(SizedBox(height: 20));
    }
    if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_TEXT)) {
      options.add(Tooltip(
          padding: EdgeInsets.all(8),
          // Tooltip 内边距
          margin: EdgeInsets.all(12),
          preferBelow: false,
          waitDuration: Duration(milliseconds: 200),
          decoration: BoxDecoration(
              color: Color.fromARGB(241, 236, 241, 241), // 装饰颜色
              borderRadius: BorderRadius.circular(8)),
          richMessage: TextSpan(
            text: (reference.innerText ?? '').replaceAll('<br>', '\n'),
            style: TextStyle(
                fontSize: 17,
                height: 1.7,
                color: (Get.isDarkMode ? Color(0xFF757575) : Colors.black87)),
          ),
          child: HtmlWidget(reference.text ?? '',
              textStyle: TextStyle(
                  fontSize: 18,
                  color: (Get.isDarkMode ? Color(0xFF757575) : Colors.black87),
                  height: 1.8,
                  wordSpacing: 1.5))));
    }
    if (show.contains(QuestionContent.QUESTION_SHOW_TYPE_IMAGE) &&
        reference.image != null) {
      options
          .add(BGExamImageWidget(imgUrl: reference.image, source: 'Reference'));
      options.add(SizedBox(height: 20));
    }

    return Container(
        margin: EdgeInsets.only(bottom: 20, left: 30, right: 20),
        child: BGDashedRectWidget(
            child: Container(
                margin: EdgeInsets.all(20), child: Column(crossAxisAlignment: CrossAxisAlignment.start,children: options))));
  }
}

class CardWidget extends StatelessWidget {
  final Widget child;

  const CardWidget({
    required this.child,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    //阅读测试题外框
    return Container(
      decoration: BoxDecoration(
          border: Border.all(width: 1, color: Color(0xffcccccc)),
          borderRadius: BorderRadius.circular(3)),
      margin: EdgeInsets.only(bottom: 20),
      child: Container(
        child: child,
        padding: EdgeInsets.fromLTRB(0, 10, 10, 20),
      ),
    );
  }
}
